package com.xykj.enterprise.wechat.util.other;

/**
 * @author Feng Chen
 */
public abstract class HexUtil {

    private HexUtil() {

    }

    /**
     * 十六进制字符串转字节数组
     *
     * @param hex
     * @return
     */
    public static byte[] hexToByteArray(String hex) {
        byte[] result = new byte[hex.length() / 2];
        for (int len = hex.length(), index = 0; index <= len - 1; index += 2) {
            String subString = hex.substring(index, index + 2);
            int intValue = Integer.parseInt(subString, 16);
            result[index / 2] = (byte) intValue;
        }
        return result;
    }

    /**
     * 字节数组转十六进制字符串
     *
     * @param bytes
     * @return
     */
    public static String byteArrayToHex(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString().toUpperCase();
    }

}
